extern crate reqwest; extern crate tokio; extern crate anyhow;


use anyhow::Result;
use clap::Parser;
use std::time::Instant;
use colored::Colorize;
use multi_thread_http::{Args, HttpRequestHandler};

// 定义用于测试的请求结构体
#[derive(serde::Serialize)]
struct TestRequest {
    name: String,
    value: i32,
}

// 定义用于测试的响应结构体
#[derive(serde::Deserialize)]
struct TestResponse {
    name: String,
    value: i32,
    success: bool,
}

#[tokio::main]
async fn main() -> Result<()> {
    // 解析命令行参数
    let args = Args::parse();
    
    // 将逗号分隔的URL字符串转换为Vec<String>
    let urls: Vec<String> = args.urls.split(',').map(|s| s.trim().to_string()).collect();
    
    // 创建请求处理实例
    let handler = HttpRequestHandler::new(args.concurrency);
    
    // 测试post_json方法
    if !urls.is_empty() {
        let test_url = urls[0].clone();
        let test_request = TestRequest {
            name: "test_name".to_string(),
            value: 42,
        };
        
        match handler.post_json::<TestRequest, TestResponse>(test_url, test_request).await {
            Ok(response) => {
                println!("POST request succeeded:");
                println!("Name: {}", response.name.green());
                println!("Value: {}", response.value.to_string().green());
                println!("Success: {}", response.success.to_string().green());
            },
            Err(e) => {
                eprintln!("Error during POST request: {}", e.to_string().red());
            }
        }
    }
    
    // 循环执行指定次数
    for i in 0..args.iterations {
        println!("\nIteration {} of {}:", i + 1, args.iterations);
        
        // 记录开始时间
        let start_time = Instant::now();
        
        // 执行并发请求
        match handler.fetch_all(urls.clone()).await {
            Ok(results) => {
                // 打印每个URL的结果
                for (url, size) in results {
                    println!("{} - Response size: {} bytes", url.green(), size);
                }
            },
            Err(e) => {
                eprintln!("Error during requests: {}", e.to_string().red());
            }
        }
        
        // 计算并打印耗时
        let duration = start_time.elapsed();
        println!("Completed in {:.2?} seconds", duration.as_secs_f64());
        
        // 如果不是最后一次迭代，添加延迟
        if i < args.iterations - 1 {
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
        }
    }
    
    Ok(())
}
